package com.study.mike.service.impl;


import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.study.mike.common.utils.RedisUtil;
import com.study.mike.mapper.UserMapper;
import com.study.mike.model.dto.ImportUserInfoListener;
import com.study.mike.model.dto.UserDTO;
import com.study.mike.model.entity.MidUser;
import com.study.mike.model.entity.One;
import com.study.mike.model.entity.User;
import com.study.mike.model.po.UserImportPO;
import com.study.mike.model.query.UserQuery;
import com.study.mike.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.io.IOException;
import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author kh
 * @since 2021-12-29
 */
@Validated
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Resource
    private UserMapper userMapper;
    @Resource
    private RedisUtil redisUtil;

    @Override
    public List<User> queryInfo() {
        return userMapper.selectList(null);
    }

    @Override
    public IPage<UserDTO> pageQuery(UserQuery query) {
        Page<User> page = new Page<>(query.getPageCurrent(), query.getPageSize());
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        if (query.getName() != null && query.getName() != "") {
            queryWrapper.eq(User::getName, query.getName());
        }
        if (query.getEmail() != null && query.getEmail() != "") {
            queryWrapper.eq(User::getEmail, query.getEmail());
        }
        IPage<User> userPages = userMapper.selectPage(page, queryWrapper);
        // 拿到的数据对想为User，将其转化为UserDTO;
        // 方法1:获取原page的records对象为一个list，将其转化为响应的实体list，然后定义对应的page<>对象，完成相关属性的填充
//        List<User> userList = userPages.getRecords();
//        List<UserDTO> userDTOS = new ArrayList<>(100);
//        userList.stream().forEach(item -> {
//            UserDTO userDTO = new UserDTO();
//            BeanUtils.copyProperties(item, userDTO);
//            userDTOS.add(userDTO);
//        });
//        IPage<UserDTO> userDTOIPage = new Page<>();
//        userDTOIPage.setRecords(userDTOS);
//        userDTOIPage.setTotal(userPages.getTotal());
//        userDTOIPage.setSize(userPages.getSize());
//        return userDTOIPage;

        // 方法2、通过stream流完成list的转化
        List<UserDTO> userDTOS = userPages.getRecords().stream().map(x -> {
            UserDTO userDTO = new UserDTO();
            BeanUtils.copyProperties(x, userDTO);
            return userDTO;
        }).collect(Collectors.toList());
        IPage<UserDTO> userDTOIPage = new Page<>();
        userDTOIPage.setRecords(userDTOS);
        userDTOIPage.setTotal(userPages.getTotal());
        userDTOIPage.setSize(userPages.getSize());
        return userDTOIPage;
    }

    @Override
    public boolean exportUser() throws IOException {
        return true;
    }


    @Override
    public boolean importUser() throws Exception {
        // 获取到文件路径
        String filePath = "C:\\Users\\James\\Desktop\\20230323161852337.xlsx";
        ImportUserInfoListener userInfoListener = new ImportUserInfoListener();
        EasyExcel.read(filePath, UserImportPO.class, userInfoListener).sheet().doRead();
        // 获取导入的数据
        List<UserImportPO> userImportPOS = userInfoListener.getUserList();
        List<User> users = JSONUtil.toList(JSONUtil.toJsonStr(userImportPOS), User.class);
        this.saveBatch(users);
        return true;
    }

    @Override
    public Boolean one(@Valid One one) {
        System.out.println("哈哈");
        return true;
    }

    @Override
    public Boolean add(User user) {
        // 获取到加密字段
        this.save(user);
        return true;
    }

    @Override
    public void test111() {
        User user = new User();
        user.setName("test");
        user.setNameSensitive("11");
        user.setEmailSensitive("123");
        user.setAge(1);
        User user1 = new User();
        user1.setName("test");
        user1.setNameSensitive("11");
        user1.setEmailSensitive("123");
        user1.setAge(1);
        Set<User> set = new HashSet<>();
        set.add(user);
        set.add(user1);
        System.out.println(set.size());


    }

    @Override
    public Boolean add1(MidUser user) {
        this.save(user);
        return true;
    }

    @Override
    public List<User> getUserInfoByRedis() {
        return (List<User>) redisUtil.get("user");
    }

    @Override
    public Boolean updateUser(User user) {
        return this.updateById(user);
    }

    @Override
    public String changeMoney(String money) {
        return this.getMoney(money);
    }

    @Override
    public Boolean encryptName() {
        List<User> list = userMapper.selectList(null);
        List<User> updates = new ArrayList<>();
        list.forEach(item -> {
            updates.add(item);
        });
        this.updateBatchById(updates);
        return true;
    }

    @Override
    public String exportUserInfo() {
        // 获取到导出数据
        List<User> users = this.queryInfo();
        // 命名文件
        String exportFileName = "C:\\Users\\James\\Desktop\\" + DateUtil.format(new Date(), DatePattern.PURE_DATETIME_MS_PATTERN) + ".xlsx";
        EasyExcel.write(exportFileName, User.class).sheet().doWrite(users);
        return exportFileName;
    }

    /**
     * 元转换成分
     *
     * @param amount
     * @return
     */
    public String getMoney(String amount) {
        if (amount == null) {
            return "";
        }
        // 金额转化为分为单位
        // 处理包含, ￥ 或者$的金额
        String currency = amount.replaceAll("\\$|\\￥|\\,", "");
        int index = currency.indexOf(".");
        int length = currency.length();
        Long amLong = 0L;
        if (index == -1) {
            amLong = Long.valueOf(currency + "00");
        } else if (length - index >= 3) {
            amLong = Long.valueOf((currency.substring(0, index + 3)).replace(".", ""));
        } else if (length - index == 2) {
            amLong = Long.valueOf((currency.substring(0, index + 2)).replace(".", "") + 0);
        } else {
            amLong = Long.valueOf((currency.substring(0, index + 1)).replace(".", "") + "00");
        }
        return amLong.toString();
    }

}
